package services

import (
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promauto" // 添加此导入
	dto "github.com/prometheus/client_model/go"
	"saasems/database"
	"time"
	// 添加此导入
)

var (
	messagesReceived = promauto.NewCounter(prometheus.CounterOpts{
		Name: "saasems_messages_received_total",
		Help: "Total number of MQTT messages received",
	})

	messagesProcessed = promauto.NewCounter(prometheus.CounterOpts{
		Name: "saasems_messages_processed_total",
		Help: "Total number of messages processed successfully",
	})

	processingTime = promauto.NewHistogram(prometheus.HistogramOpts{
		Name:    "saasems_message_processing_time_seconds",
		Help:    "Time taken to process a message",
		Buckets: prometheus.ExponentialBuckets(0.001, 2, 15),
	})

	messagesPerSecond = promauto.NewGauge(prometheus.GaugeOpts{
		Name: "saasems_messages_processed_per_second",
		Help: "Number of messages processed per second",
	})
)

type MetricsStorage struct {
	db *database.PostgresDB
}

func NewMetricsStorage(db *database.PostgresDB) *MetricsStorage {
	return &MetricsStorage{db: db}
}

func (s *MetricsStorage) SaveMetrics() error {
	metrics := map[string]float64{
		"messages_received":   getCounterValue(messagesReceived),
		"messages_processed":  getCounterValue(messagesProcessed),
		"messages_per_second": getGaugeValue(messagesPerSecond),
	}

	for name, value := range metrics {
		s.db.GetDB().Exec(
			"INSERT INTO metrics (name, value, timestamp) VALUES ($1, $2, $3)",
			name, value, time.Now(),
		)
	}
	return nil
}

func getCounterValue(c prometheus.Counter) float64 {
	var m = &dto.Metric{}
	if err := c.Write(m); err != nil {
		return 0
	}
	return m.Counter.GetValue()
}

func getGaugeValue(g prometheus.Gauge) float64 {
	var m = &dto.Metric{}
	if err := g.Write(m); err != nil {
		return 0
	}
	return m.Gauge.GetValue()
}
